import geopandas as gpd
import matplotlib.pyplot as plt
import mpld3
import pandas as pd
import pandas_profiling as pp
import pyproj
from geopandas import GeoDataFrame


# 提供文件路径 读geojson格式的地理数据 返回geodataframe
def read_geodata(geo_path):
    gdf = gpd.read_file(geo_path)
    print(gdf.head())
    return gdf


# 可以对传入数据进行探索性分析生成名为dataProfileReport.html的探索性分析报告
def dataProfileReport(gdf):
    pfr = pp.ProfileReport(gdf)
    pfr.to_file('dataProfileReport.html')
    return pfr


# 提供路径读取csv文件并转点 csv_path csv路径 save_path 转点后geojson的保存路径
def csvtoPoint(csv_path, save_path='null'):
    df_csv = pd.read_csv(csv_path, encoding='utf-8')
    gdf_point: GeoDataFrame = gpd.GeoDataFrame(df_csv, geometry=gpd.points_from_xy(df_csv.lon, df_csv.wgs_84_lat))
    gdf_point.crs = pyproj.CRS.from_user_input('EPSG:4326')
    print(gdf_point.head())
    if save_path == 'null':
        print('unsaved')
    else:
        gdf_point.to_file(save_path, driver='GeoJSON', encoding="utf-8")
    return gdf_point


# 空间连接 gdf_Point 点 gdf 面 classify 分类依据 groupby 分组统计依据 返回连接好的面
def SpatialJoin_group(gdf,gdf_point, classify, groupby, title='count'):
    sj_gdf: GeoDataFrame = gpd.sjoin(gdf, gdf_point, how='left', op='intersects', lsuffix='left', rsuffix='right')
    gdf_sj = sj_gdf[classify].groupby([sj_gdf[groupby]]).count()
    gdf = gdf.join(gdf_sj, on=groupby)
    gdf.rename(columns={classify: 'count'}, inplace=True)
    print(gdf.head())
    fig, ax = plt.subplots(figsize=(12, 10), subplot_kw={'aspect': 'equal'})
    plt.title(title)
    gdf.plot(column='count', scheme='Quantiles', k=8, cmap='GnBu', legend=True, ax=ax)
    #mpld3.fig_to_html(fig)
    return gdf